package com.alibaba.citrus.ots.sales.plan.facade.service.salesplan.adjust;

import com.alibaba.citrus.ots.common.annotation.EpochTransactional;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.model.ImportRequest;
import com.alibaba.citrus.ots.sales.plan.annotation.CommonRedisLock;
import com.alibaba.citrus.ots.sales.plan.api.salesplan.adjust.SalesPlanAdjustDetailFileService;
import com.alibaba.citrus.ots.sales.plan.api.salesplan.adjust.SalesPlanAdjustDetailWriteService;
import com.alibaba.citrus.ots.sales.plan.api.setting.SalesPlanScItemQueryService;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.BatchQuerySalesPlanRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.BatchQuerySalesPlanScItemRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.ChangePasswordRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.FirstLoginEmailRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.PageQueryAdjustmentDetailsRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.ResetPasswordEmailRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanAdjustDetailBatchQueryRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanAdjustDetailExportRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanAdjustImportRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.request.SalesPlanImportRequest;
import com.alibaba.citrus.ots.sales.plan.dto.api.response.SalesPlanAdjustDetailExportResponse;
import com.alibaba.citrus.ots.sales.plan.facade.service.SalesPlanOutCommonService;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalesPlanModelEnum;
import com.alibaba.citrus.ots.sales.plan.model.enums.SalesStatBizTypeEnum;
import com.alibaba.citrus.ots.sales.plan.repository.*;
import com.alibaba.citrus.ots.sales.plan.sdo.*;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.middleware.mq.runtime.EpochMessageService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.contants.BcOtsConstants;
import com.epoch.app.bcots.model.dto.BaselineGetEmployeeByIdsAllRequest;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIdsAllRequest;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIdsAllResponse;
import com.epoch.app.bcots.model.dto.EmployeeResetPasswordsRequest;
import com.epoch.app.bcots.model.dto.OrganizationSDO;
import com.epoch.app.bcots.model.dto.PageQuerySalesPlanAdjustDetailRequest;
import com.epoch.app.bcots.model.dto.PageQuerySalesPlanAdjustDetailResponse;
import com.epoch.app.bcots.model.dto.QueryEmployeeAndOrganizationRequest;
import com.epoch.app.bcots.model.dto.QueryEmployeeAndOrganizationResponse;
import com.epoch.app.bcots.model.dto.ScItemSDO;
import com.epoch.app.bcots.sales_plan.notificationconfig.dto.BoNotificationConfigGetListRequest;
import com.epoch.app.bcots.sales_plan.notificationconfig.dto.BoNotificationConfigGetListResponse;
import com.epoch.app.bcots.sales_plan.notificationconfig.service.NotificationConfigService;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.BcOtsService;
import com.epoch.app.bcots.service.SalesPlanService;
import com.epoch.app.otsplatformenhance.model.dto.CustomerAddressIndex;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.alibaba.citrus.ots.sales.plan.contants.SalesPlanLockKey.ADJUSTMENT_WRITE_EASY_EXCEL_FILE_PREFIX;

@Service
public class SalesPlanAdjustDetailFileServiceImpl implements SalesPlanAdjustDetailFileService {
    private static final Log log = Log.getLogger(SalesPlanAdjustDetailFileService.class);

    @Resource
    private BcOtsService bcOtsService;

    @Resource
    private EpochCacheService epochCacheService;

    @Resource
    private SalesPlanAdjustDetailFileRepository salesPlanAdjustDetailFileRepository;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private SalesPlanScItemQueryService salesPlanScItemQueryService;

    @Resource
    private SalesPlanRepository salesPlanRepository;

    @Resource
    private SalesPlanAdjustDetailWriteService salesPlanAdjustDetailWriteService;

    @Resource
    private SalesPlanService salesPlanService;

    @Resource
    private SalesPlanOutCommonService salesPlanOutCommonService;

    @Resource
    private NotificationConfigService notificationConfigService;

    @Resource
    private EpochMessageService messageService;

    @Resource
    private SalesPlanAdjustDetailRepository salesPlanAdjustDetailRepository;

    @Resource
    private PlatformEnhanceRepository platformEnhanceRepository;

    @Resource
    private SendHistoryRecordRepository sendHistoryRecordRepository;


    @Override
    @FacadeInvoker
    @EpochTransactional(appCode = "bc_ots", dataSourceCode = "cr_ots", dataSourceType = "app")
    @CommonRedisLock(redisLockPrefix = ADJUSTMENT_WRITE_EASY_EXCEL_FILE_PREFIX)
    public Result<SendMailSDO> adjustmentWriteEasyExcelFile(PageQueryAdjustmentDetailsRequest pageQueryAdjustmentDetailsRequest) {
        Result<SendMailSDO> result;
        // 发送邮件
        try {
            result = salesPlanAdjustDetailFileRepository.adjustmentWriteEasyExcelFile(pageQueryAdjustmentDetailsRequest);
        } catch (Exception e) {
            log.error("SalesPlanReportWriteServiceImpl#adjustmentWriteEasyExcelFile_fail " + "发送邮件异常", e);
            throw e;
        }

        // 发消息，触发汇总
        try {
            log.info("SalesPlanAdjustDetailFileServiceImpl.adjustmentWriteEasyExcelFile-planId:{}", pageQueryAdjustmentDetailsRequest.getPlanId());
            Boolean aBoolean = messageService.sendMessage("sales_plan_publish_message", "CR_SALES_PLAN", "salesPlan_collect", pageQueryAdjustmentDetailsRequest.getPlanId());
        } catch (Exception e) {
            log.error("SalesPlanReportWriteServiceImpl#adjustmentWriteEasyExcelFile_fail " + "邮件通知大区触发月度计划汇总消息发送异常", e);
        }
        return result;
    }

    @Override
    @FacadeInvoker
    public Result<List<SalesPlanAdjustImportRequest>> salesPlanAdjustImportHandle(List<SalesPlanAdjustImportRequest> requestList, SalesPlanImportRequest salesPlanImportRequest) {
        if (CollectionUtils.isEmpty(requestList)) {
            return Result.success(Lists.newArrayList());
        }
        Set<String> scItemSet = Sets.newHashSet();
        Set<String> customerAddressSet = Sets.newHashSet();
        Set<String> customerSet = Sets.newHashSet();
        Set<String> orgSalesOrganizationCodeSet = Sets.newHashSet();
        Set<String> channelCodeSet = Sets.newHashSet();
        Set<String> itemGroupSet = Sets.newHashSet();
        //校验必传参数
        List<SalesPlanAdjustImportRequest> checkRequestList = new ArrayList<>();
        for (SalesPlanAdjustImportRequest salesPlanAdjustImportRequest : requestList) {
            if (Strings.isBlank(salesPlanAdjustImportRequest.getAdjustId())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-004", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustImportRequest.setAdjustId(salesPlanAdjustImportRequest.getAdjustId().trim());
            }

            if (!salesPlanAdjustImportRequest.getAdjustId().trim().equals(salesPlanImportRequest.getAdjustId())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-017", null).getDisplayErrorMessage());
                continue;
            }

            if (Strings.isBlank(salesPlanAdjustImportRequest.getCustomerCode())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-005", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustImportRequest.setCustomerCode(salesPlanAdjustImportRequest.getCustomerCode().trim());
            }

            if (Strings.isBlank(salesPlanAdjustImportRequest.getCustomerAddress())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-006", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustImportRequest.setCustomerAddress(salesPlanAdjustImportRequest.getCustomerAddress().trim());
            }

            if (Strings.isBlank(salesPlanAdjustImportRequest.getScItemId())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-003", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustImportRequest.setScItemId(salesPlanAdjustImportRequest.getScItemId().trim());
            }

            if (Strings.isBlank(salesPlanAdjustImportRequest.getChannelCode())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-030", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustImportRequest.setChannelCode(salesPlanAdjustImportRequest.getChannelCode().trim());
            }

            if (Strings.isBlank(salesPlanAdjustImportRequest.getOrgSalesOrganizationOutCode())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-029", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustImportRequest.setOrgSalesOrganizationOutCode(salesPlanAdjustImportRequest.getOrgSalesOrganizationOutCode().trim());
            }

            if (Strings.isBlank(salesPlanAdjustImportRequest.getItemGroup())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-16-031", null).getDisplayErrorMessage());
                continue;
            } else {
                salesPlanAdjustImportRequest.setItemGroup(salesPlanAdjustImportRequest.getItemGroup().trim());
            }

            if (null == salesPlanAdjustImportRequest.getMonthFirstAdjustCount()) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-026", null).getDisplayErrorMessage());
                continue;
            }

            if (null == salesPlanAdjustImportRequest.getMonthMiddleAdjustCount()) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-027", null).getDisplayErrorMessage());
                continue;
            }

            if (null == salesPlanAdjustImportRequest.getMonthLastAdjustCount()) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-028", null).getDisplayErrorMessage());
                continue;
            }

            scItemSet.add(salesPlanAdjustImportRequest.getScItemId());
            customerAddressSet.add(salesPlanAdjustImportRequest.getCustomerAddress());
            customerSet.add(salesPlanAdjustImportRequest.getCustomerCode());
            orgSalesOrganizationCodeSet.add(salesPlanAdjustImportRequest.getOrgSalesOrganizationOutCode());
            channelCodeSet.add(salesPlanAdjustImportRequest.getChannelCode());
            itemGroupSet.add(salesPlanAdjustImportRequest.getItemGroup());
            checkRequestList.add(salesPlanAdjustImportRequest);
        }
        if (CollectionUtils.isEmpty(checkRequestList)) {
            return Result.success(requestList);
        }
        //销售组织外部编码 置换 内部ID
        Map<String, com.epoch.app.otsplatformenhance.sdo.OrganizationSDO> organizationMapByOutCode = salesPlanOutCommonService.getOrganizationMapByOutCode(orgSalesOrganizationCodeSet);
        if (organizationMapByOutCode == null) {
            log.error("SalesPlanAdjustDetailFileServiceImpl.salesPlanAdjustImportHandle.orgSalesOrganizationCodeResult nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList, ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        //批量查货品，换取scItemId
        Map<String, ScItemSDO> scItemMap = salesPlanOutCommonService.getScItemMapByOutId(scItemSet);
        if (scItemMap == null) {
            log.error("SalesPlanAdjustDetailFileServiceImpl.salesPlanAdjustImportHandle.scItemResult nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList, ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        //客户收获地址
        //查询 客户地址 (五键唯一)
        Set<String> organizationIdList = organizationMapByOutCode.values().stream().map(com.epoch.app.otsplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toSet());
        Map<String, CustomerAddressIndex> customerAddressMap = salesPlanOutCommonService.getCustomerAddressByFive(customerAddressSet, customerSet, organizationIdList, channelCodeSet, itemGroupSet);
        if (customerAddressMap == null) {
            log.error("SalesPlanLineFileServiceImpl.salesPlanLineImportHandle.customerAddressResult nothingness");
            ImportRequest.setRequestErrorMessage(checkRequestList, ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        //获取客户地址对应的组织
        List<SalesPlanAdjustImportRequest> checkSalesPlanAdjustImportRequest = new ArrayList<>();
        for (SalesPlanAdjustImportRequest salesPlanAdjustImportRequest : checkRequestList) {
            com.epoch.app.otsplatformenhance.sdo.OrganizationSDO organization = organizationMapByOutCode.get(salesPlanAdjustImportRequest.getOrgSalesOrganizationOutCode());
            if (organization == null) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-006", null).getDisplayErrorMessage());
                continue;
            }
            CustomerAddressIndex customerAddressSDO = customerAddressMap.get(salesPlanAdjustImportRequest.getCustomerCode() + salesPlanAdjustImportRequest.getCustomerAddress() + organization.getId() + salesPlanAdjustImportRequest.getChannelCode() + salesPlanAdjustImportRequest.getItemGroup());
            if (Objects.isNull(customerAddressSDO)) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-002", null).getDisplayErrorMessage());
                continue;
            }
            //权限校验
            if (salesPlanImportRequest.getBizType() == null && StringUtil.isBlank(salesPlanImportRequest.getBizId())) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-007", null).getDisplayErrorMessage());
                continue;
            }
            //业务单元以上的能查看所有数据(权限控制)
            if (salesPlanImportRequest.getBizType() >= SalesStatBizTypeEnum.BUSINESS_UNIT.getOrganizationType()) {
                SalesStatBizTypeEnum byOrganizationType = SalesStatBizTypeEnum.getByOrganizationType(salesPlanImportRequest.getBizType());
                if (byOrganizationType == null) {
                    salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-007", null).getDisplayErrorMessage());
                    continue;
                }
                boolean isContinue = false;
                switch (byOrganizationType) {
                    case SALESMAN:
                        if (StringUtil.isBlank(customerAddressSDO.getPrincipal())) {
                            salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-028", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getPrincipal().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_DEPARTMENT:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleDepartmentCode())) {
                            salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-029", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleDepartmentCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_CHANNEL:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleChannelCode())) {
                            salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-030", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleChannelCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case SALES_ORGANIZATION:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgSaleOrganizationCode())) {
                            salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-031", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgSaleOrganizationCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    case BUSINESS_UNIT:
                        if (StringUtil.isBlank(customerAddressSDO.getOrgBussinessUnitCode())) {
                            salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-032", null).getDisplayErrorMessage());
                            isContinue = true;
                        } else {
                            if (!customerAddressSDO.getOrgBussinessUnitCode().equals(salesPlanImportRequest.getBizId())) {
                                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-02-15-027", null).getDisplayErrorMessage());
                                isContinue = true;
                            }
                        }
                        break;
                    default:
                }
                if (isContinue) {
                    continue;
                }
            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getOrgBussinessUnitCode())) {
                salesPlanAdjustImportRequest.setOrgBusinessUnitCode(customerAddressSDO.getOrgBussinessUnitCode());
            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getOrgSaleOrganizationCode())) {
                salesPlanAdjustImportRequest.setOrgSaleOrganizationCode(customerAddressSDO.getOrgSaleOrganizationCode());
            }
            if (StringUtil.isNotEmpty(customerAddressSDO.getOrgSaleChannelCode())) {
                salesPlanAdjustImportRequest.setOrgSaleChannelCode(customerAddressSDO.getOrgSaleChannelCode());
            }
            if (StringUtil.isNotEmpty(Objects.toString(customerAddressSDO.getId(), null))) {
                salesPlanAdjustImportRequest.setCustomerAddressId(Objects.toString(customerAddressSDO.getId(), null));
            }
            checkSalesPlanAdjustImportRequest.add(salesPlanAdjustImportRequest);
        }
        if (CollectionUtils.isEmpty(checkSalesPlanAdjustImportRequest)) {
            return Result.success(requestList);
        }
        //货品范围
        List<String> scItemIdList = scItemMap.values().stream().map(ScItemSDO::getScItemId).distinct().collect(Collectors.toList());
        List<String> orgBusinessUnitCodeList = checkSalesPlanAdjustImportRequest.stream().map(SalesPlanAdjustImportRequest::getOrgBusinessUnitCode).distinct().collect(Collectors.toList());
        List<String> orgSaleOrganizationCodeList = checkSalesPlanAdjustImportRequest.stream().map(SalesPlanAdjustImportRequest::getOrgSaleOrganizationCode).distinct().collect(Collectors.toList());
        List<String> orgSaleChannelCodeList = checkSalesPlanAdjustImportRequest.stream().map(SalesPlanAdjustImportRequest::getOrgSaleChannelCode).distinct().collect(Collectors.toList());

        BatchQuerySalesPlanScItemRequest batchQuerySalesPlanScItemRequest = new BatchQuerySalesPlanScItemRequest();
        batchQuerySalesPlanScItemRequest.setScItemIds(scItemIdList);
        batchQuerySalesPlanScItemRequest.setOrgBusinessUnitCodeList(orgBusinessUnitCodeList);
        batchQuerySalesPlanScItemRequest.setOrgSaleOrganizationCodeList(orgSaleOrganizationCodeList);
        batchQuerySalesPlanScItemRequest.setOrgSaleChannelCodeList(orgSaleChannelCodeList);
        //启用状态的数据
        batchQuerySalesPlanScItemRequest.setStatus(1);
        Result<List<SalesPlanScItemSDO>> salesPlanScItemResult = salesPlanScItemQueryService.batchQuerySalesPlanScItem(batchQuerySalesPlanScItemRequest);
        if (salesPlanScItemResult == null || !salesPlanScItemResult.isSuccess() || salesPlanScItemResult.getResult() == null || salesPlanScItemResult.getResult().size() == 0) {
            log.error("SalesPlanLineFileServiceImpl.salesPlanLineImportHandle.salesPlanScItemResult nothingness");
            ImportRequest.setRequestErrorMessage(checkSalesPlanAdjustImportRequest, ErrorMessage.code("OTS-02-001-00-15-005", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        Map<String, SalesPlanScItemSDO> salesPlanScItemMap = salesPlanScItemResult.getResult().stream().collect(Collectors.toMap(x -> x.getOrgBusinessUnitCode() + x.getOrgSalesOrganizationCode() + x.getOrgSalesChannelCode() + x.getScItemId(), a -> a, (a, b) -> a));

        //校验调整ID是否存在
        Set<String> adjustIdSet = checkRequestList.stream().map(SalesPlanAdjustImportRequest::getAdjustId).collect(Collectors.toSet());
        BatchQuerySalesPlanRequest batchQuerySalesPlanRequest = new BatchQuerySalesPlanRequest();
        batchQuerySalesPlanRequest.setIds(Lists.newArrayList(adjustIdSet));
        batchQuerySalesPlanRequest.setModel(SalesPlanModelEnum.ADJUST_MODEL.getModel());
        List<SalesPlanSDO> salesPlanSDOList = salesPlanRepository.batchQuerySalesPlan(batchQuerySalesPlanRequest);
        if (salesPlanSDOList == null || salesPlanSDOList.size() == 0) {
            log.error("SalesPlanLineFileServiceImpl.salesPlanLineImportHandle.salesPlanSDOList nothingness");
            ImportRequest.setRequestErrorMessage(checkSalesPlanAdjustImportRequest, ErrorMessage.code("OTS-02-005-00-15-005", null).getDisplayErrorMessage());
            return Result.success(requestList);
        }
        Map<Long, SalesPlanSDO> salesPlanSDOMap = salesPlanSDOList.stream().collect(Collectors.toMap(SalesPlanSDO::getId, a -> a, (a, b) -> a));

        //如果是修改的数据需要做任务量+调整量<0的校验
        //adjustId+客户收收获地址编码+货品编码查询重复数据，重复则更新，否则新增
        Set<Long> adjustIdSet2 = checkSalesPlanAdjustImportRequest.stream().map(SalesPlanAdjustImportRequest::getAdjustId).map(Long::valueOf).collect(Collectors.toSet());
        Set<String> customerAddresSet = checkSalesPlanAdjustImportRequest.stream().map(SalesPlanAdjustImportRequest::getCustomerAddress).collect(Collectors.toSet());
        Set<String> scItemIdSet = scItemMap.values().stream().map(ScItemSDO::getScItemId).collect(Collectors.toSet());
        Set<String> customerAddressIdSet = checkSalesPlanAdjustImportRequest.stream().map(SalesPlanAdjustImportRequest::getCustomerAddressId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());

        SalesPlanAdjustDetailBatchQueryRequest salesPlanAdjustDetailBatchQueryRequest = new SalesPlanAdjustDetailBatchQueryRequest();
        salesPlanAdjustDetailBatchQueryRequest.setAdjustIds(com.alibaba.acm.shaded.com.google.common.collect.Lists.newArrayList(adjustIdSet2));
        salesPlanAdjustDetailBatchQueryRequest.setCustomerAddress(com.alibaba.acm.shaded.com.google.common.collect.Lists.newArrayList(customerAddresSet));
        salesPlanAdjustDetailBatchQueryRequest.setScItemIds(com.alibaba.acm.shaded.com.google.common.collect.Lists.newArrayList(scItemIdSet));
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(customerAddressIdSet)) {
            salesPlanAdjustDetailBatchQueryRequest.setCustomerAddressId(com.alibaba.acm.shaded.com.google.common.collect.Lists.newArrayList(customerAddressIdSet));
        }
        Map<String, SalesPlanAdjustDetailSDO> salesPlanAdjustMap = salesPlanAdjustDetailRepository.batchQueryDetail(salesPlanAdjustDetailBatchQueryRequest).stream()
                .collect(Collectors.toMap(x -> {
                    StringBuilder builder = new StringBuilder(x.getAdjustId().toString());
                    if (StringUtils.isNotBlank(x.getCustomerAddressId())) {
                        builder.append(x.getCustomerAddressId());
                    }
                    builder.append(x.getCustomerAddress()).append(x.getScItemId());
                    return builder.toString();
                }, a -> a, (a, b) -> a));
        //数据填充
        List<SalesPlanAdjustDetailSDO> salesPlanAdjustDetailSDOList = new ArrayList<>();
        Map<String, SalesPlanAdjustDetailSDO> salesPlanAdjustDetailSDOMap = new HashMap<>();
        for (SalesPlanAdjustImportRequest salesPlanAdjustImportRequest : checkSalesPlanAdjustImportRequest) {
            com.epoch.app.otsplatformenhance.sdo.OrganizationSDO organization = organizationMapByOutCode.get(salesPlanAdjustImportRequest.getOrgSalesOrganizationOutCode());
            //地址
            CustomerAddressIndex customerAddressSDO = customerAddressMap.get(salesPlanAdjustImportRequest.getCustomerCode() + salesPlanAdjustImportRequest.getCustomerAddress() + organization.getId() + salesPlanAdjustImportRequest.getChannelCode() + salesPlanAdjustImportRequest.getItemGroup());

            //货品
            ScItemSDO scItem = scItemMap.get(salesPlanAdjustImportRequest.getScItemId());
            if (Objects.isNull(scItem)) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-005-02-15-001", null).getDisplayErrorMessage());
                continue;
            }
            //计划货品
            SalesPlanScItemSDO salesPlanScItemSDO = salesPlanScItemMap.get(customerAddressSDO.getOrgBussinessUnitCode() + customerAddressSDO.getOrgSaleOrganizationCode() + customerAddressSDO.getOrgSaleChannelCode() + scItem.getScItemId());
            if (Objects.isNull(salesPlanScItemSDO)) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-001-00-15-005", null).getDisplayErrorMessage());
                continue;
            }
            //计划
            SalesPlanSDO planSDO = salesPlanSDOMap.get(Long.parseLong(salesPlanAdjustImportRequest.getAdjustId()));
            if (Objects.isNull(planSDO)) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-005", null).getDisplayErrorMessage());
                continue;
            }
            //根据调整设置来校验上中下旬调整量必填
            if (Optional.ofNullable(planSDO.getMonthFirst()).orElse(true) && null == salesPlanAdjustImportRequest.getMonthFirstAdjustCount()) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-006", null).getDisplayErrorMessage());
                continue;
            }
            if (Optional.ofNullable(planSDO.getMonthFirst()).orElse(true)) {
                StringBuilder builder = new StringBuilder(salesPlanAdjustImportRequest.getAdjustId());
                if (StringUtils.isNotBlank(salesPlanAdjustImportRequest.getCustomerAddressId())) {
                    builder.append(salesPlanAdjustImportRequest.getCustomerAddressId());
                }
                builder.append(salesPlanAdjustImportRequest.getCustomerAddress()).append(scItem.getScItemId());
                String key = builder.toString();
                SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = salesPlanAdjustMap.get(key);
                if (Objects.nonNull(salesPlanAdjustDetailSDO)) {
                    //修改的数据
                    Integer monthFirstTaskCount = Optional.ofNullable(salesPlanAdjustDetailSDO.getMonthFirstTaskCount()).orElse(0);
                    if (salesPlanAdjustImportRequest.getMonthFirstAdjustCount() + monthFirstTaskCount < 0) {
                        salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-029", null).getDisplayErrorMessage());
                        continue;
                    }
                } else {
                    //新增
                    if (salesPlanAdjustImportRequest.getMonthFirstAdjustCount() < 0) {
                        salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-029", null).getDisplayErrorMessage());
                        continue;
                    }
                }
            }
            if (Optional.ofNullable(planSDO.getMonthMiddle()).orElse(true) && null == salesPlanAdjustImportRequest.getMonthMiddleAdjustCount()) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-007", null).getDisplayErrorMessage());
                continue;
            }
            if (Optional.ofNullable(planSDO.getMonthMiddle()).orElse(true)) {
                StringBuilder builder = new StringBuilder(salesPlanAdjustImportRequest.getAdjustId());
                if (StringUtils.isNotBlank(salesPlanAdjustImportRequest.getCustomerAddressId())) {
                    builder.append(salesPlanAdjustImportRequest.getCustomerAddressId());
                }
                builder.append(salesPlanAdjustImportRequest.getCustomerAddress()).append(scItem.getScItemId());
                String key = builder.toString();
                SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = salesPlanAdjustMap.get(key);
                if (Objects.nonNull(salesPlanAdjustDetailSDO)) {
                    //修改的数据
                    Integer monthMiddleTaskCount = Optional.ofNullable(salesPlanAdjustDetailSDO.getMonthMiddleTaskCount()).orElse(0);
                    if (salesPlanAdjustImportRequest.getMonthMiddleAdjustCount() + monthMiddleTaskCount < 0) {
                        salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-030", null).getDisplayErrorMessage());
                        continue;
                    }
                } else {
                    //新增
                    if (salesPlanAdjustImportRequest.getMonthMiddleAdjustCount() < 0) {
                        salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-029", null).getDisplayErrorMessage());
                        continue;
                    }
                }
            }
            if (Optional.ofNullable(planSDO.getMonthLast()).orElse(true) && null == salesPlanAdjustImportRequest.getMonthLastAdjustCount()) {
                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-008", null).getDisplayErrorMessage());
                continue;
            }

            if (Optional.ofNullable(planSDO.getMonthLast()).orElse(true)) {
                StringBuilder builder = new StringBuilder(salesPlanAdjustImportRequest.getAdjustId());
                if (StringUtils.isNotBlank(salesPlanAdjustImportRequest.getCustomerAddressId())) {
                    builder.append(salesPlanAdjustImportRequest.getCustomerAddressId());
                }
                builder.append(salesPlanAdjustImportRequest.getCustomerAddress()).append(scItem.getScItemId());
                String key = builder.toString();
                SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = salesPlanAdjustMap.get(key);
                if (Objects.nonNull(salesPlanAdjustDetailSDO)) {
                    //修改的数据
                    Integer monthLastTaskCount = Optional.ofNullable(salesPlanAdjustDetailSDO.getMonthLastTaskCount()).orElse(0);
                    if (salesPlanAdjustImportRequest.getMonthLastAdjustCount() + monthLastTaskCount < 0) {
                        salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-031", null).getDisplayErrorMessage());
                        continue;
                    }
                } else {
                    //新增
                    if (salesPlanAdjustImportRequest.getMonthLastAdjustCount() < 0) {
                        salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-005-00-15-029", null).getDisplayErrorMessage());
                        continue;
                    }
                }
            }
//            //入参客户编码和查询出来的数据不相等不做处理
//            if (!salesPlanAdjustImportRequest.getCustomerCode().equals(customerAddressSDO.getCustomerCode())) {
//                salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-01-004-02-15-001", null).getDisplayErrorMessage());
//                continue;
//            }
            //重复数据校验
            if (MapUtils.isNotEmpty(salesPlanAdjustDetailSDOMap)) {
                SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = salesPlanAdjustDetailSDOMap.get(salesPlanAdjustImportRequest.getAdjustId() + salesPlanAdjustImportRequest.getCustomerCode() + salesPlanAdjustImportRequest.getCustomerAddress() + salesPlanAdjustImportRequest.getOrgSalesOrganizationOutCode() + salesPlanAdjustImportRequest.getChannelCode() + salesPlanAdjustImportRequest.getItemGroup() + salesPlanAdjustImportRequest.getScItemId());
                if (Objects.nonNull(salesPlanAdjustDetailSDO)) {
                    salesPlanAdjustImportRequest.setErrorMessage(ErrorMessage.code("OTS-02-002-00-15-019", null).getDisplayErrorMessage());
                    continue;
                }
            }
            SalesPlanAdjustDetailSDO salesPlanAdjustDetailSDO = SalesPlanAdjustDetailSDO.builder().build();
            BeanUtils.copyProperties(salesPlanAdjustImportRequest, salesPlanAdjustDetailSDO);
            salesPlanAdjustDetailSDO.setPlanId(Optional.ofNullable(planSDO.getParentId().toString()).orElse(null));
            salesPlanAdjustDetailSDO.setAdjustId(Optional.ofNullable(Long.valueOf(salesPlanAdjustImportRequest.getAdjustId())).orElse(0L));
            salesPlanAdjustDetailSDO.setChannelCode(Optional.ofNullable(customerAddressSDO.getChannelCode()).orElse(null));
            salesPlanAdjustDetailSDO.setOrgBusinessUnitCode(Optional.ofNullable(customerAddressSDO.getOrgBussinessUnitCode()).orElse(null));
            salesPlanAdjustDetailSDO.setOrgSalesOrganizationCode(Optional.ofNullable(customerAddressSDO.getOrgSaleOrganizationCode()).orElse(null));
            salesPlanAdjustDetailSDO.setOrgSalesChannelCode(Optional.ofNullable(customerAddressSDO.getOrgSaleChannelCode()).orElse(null));
            salesPlanAdjustDetailSDO.setOrgSalesDepartmentCode(Optional.ofNullable(customerAddressSDO.getOrgSaleDepartmentCode()).orElse(null));
            salesPlanAdjustDetailSDO.setManageEmployeeId(Optional.ofNullable(customerAddressSDO.getPrincipal()).orElse(null));
            salesPlanAdjustDetailSDO.setCustomerAddressId(Objects.toString(customerAddressSDO.getId(), null));
            salesPlanAdjustDetailSDO.setScItemId(scItem.getScItemId());
            salesPlanAdjustDetailSDO.setScItemGroup(Optional.ofNullable(salesPlanScItemSDO.getScItemGroup()).orElse(null));
            salesPlanAdjustDetailSDO.setScItemLeafCategoryId(Optional.ofNullable(salesPlanScItemSDO.getScItemLeafCategoryId()).orElse(null));
            salesPlanAdjustDetailSDO.setScItemRootCategoryId(Optional.ofNullable(salesPlanScItemSDO.getScItemRootCategoryId()).orElse(null));
            salesPlanAdjustDetailSDO.setCostInsuranceFreight(Optional.ofNullable(salesPlanScItemSDO.getCostInsuranceFreight()).orElse(0L));
            salesPlanAdjustDetailSDO.setBasicUnit(Optional.ofNullable(salesPlanScItemSDO.getBasicUnit()).orElse(null));
            salesPlanAdjustDetailSDO.setOutboundPrice(Optional.ofNullable(salesPlanScItemSDO.getOutboundPrice()).orElse(0L));
            Integer adjustCount = salesPlanAdjustImportRequest.getMonthFirstAdjustCount() + salesPlanAdjustImportRequest.getMonthMiddleAdjustCount() + salesPlanAdjustImportRequest.getMonthLastAdjustCount();
            salesPlanAdjustDetailSDO.setAdjustCount(adjustCount);
            salesPlanAdjustDetailSDO.setOuterId(salesPlanAdjustImportRequest.getScItemId());
            salesPlanAdjustDetailSDOList.add(salesPlanAdjustDetailSDO);
            salesPlanAdjustDetailSDOMap.put(salesPlanAdjustImportRequest.getAdjustId() + salesPlanAdjustImportRequest.getCustomerCode() + salesPlanAdjustImportRequest.getCustomerAddress() + salesPlanAdjustImportRequest.getOrgSalesOrganizationOutCode() + salesPlanAdjustImportRequest.getChannelCode() + salesPlanAdjustImportRequest.getItemGroup() + salesPlanAdjustImportRequest.getScItemId(), salesPlanAdjustDetailSDO);
        }
        if (CollectionUtils.isEmpty(salesPlanAdjustDetailSDOList)) {
            return Result.success(requestList);
        }
        salesPlanAdjustDetailWriteService.batchImportCreateSalesPlanAdjustDetail(salesPlanAdjustDetailSDOList);
        return Result.success(requestList);
    }

    @Override
    @FacadeInvoker
    public Result<List<SalesPlanAdjustDetailExportResponse>> salesPlanAdjustDetailExportList(SalesPlanAdjustDetailExportRequest exportRequest) {
        try {
            PageQuerySalesPlanAdjustDetailResponse salesPlanAdjustDetailResponse = salesPlanService.pageQuerySalesPlanAdjustDetail(PageQuerySalesPlanAdjustDetailRequest.builder()
                    .planId(exportRequest.getPlanId())
                    .adjustId(exportRequest.getAdjustId().toString())
                    .customerCode(exportRequest.getCustomerCode())
                    .manageEmployeeId(exportRequest.getManageEmployeeId())
                    .scItemId(exportRequest.getScItemId())
                    .scItemLeafCategoryId(exportRequest.getScItemLeafCategoryId())
                    .status(exportRequest.getStatus())
                    .bizId(exportRequest.getBizId())
                    .bizType(exportRequest.getBizType())
                    .contractDifferenceMoneyStamp(exportRequest.getContractDifferenceMoneyStamp())
                    .start(exportRequest.getStart())
                    .limit(exportRequest.getLimit()).build());
            List<SalesPlanAdjustDetailExportResponse> responses = new ArrayList<>();
            if (!salesPlanAdjustDetailResponse.getSuccess() || salesPlanAdjustDetailResponse.getTotal() == 0 || CollectionUtils.isEmpty(salesPlanAdjustDetailResponse.getResult())) {
                return Result.success(responses);
            }
            List<SalesPlanAdjustDetailExportRequest> request = JSONObject.parseArray(JSONArray.toJSONString(salesPlanAdjustDetailResponse.getResult()), SalesPlanAdjustDetailExportRequest.class);
            log.info("月度计划调整明细导出:" + JSONObject.toJSONString(request));
            //批量查询员工信息
            List<String> employeeIds = Lists.newArrayList();
            List<String> organizationIds = Lists.newArrayList();
            request.stream().forEach(x -> {
                employeeIds.add(x.getManageEmployeeId());
                organizationIds.add(x.getOrgSalesChannelCode());
                organizationIds.add(x.getOrgSalesDepartmentCode());
            });
            Map<String, com.epoch.app.bcots.model.dto.EmployeeSDO> employeeMap;
            Map<String, OrganizationSDO> organizationMap;
            Result<List<com.epoch.app.bcots.model.dto.EmployeeSDO>> employeeListResult = baseDataService.baselineGetEmployeeByIdsAll(
                    BaselineGetEmployeeByIdsAllRequest.builder().ids(employeeIds).build());
            List<com.epoch.app.bcots.model.dto.EmployeeSDO> employeeSDOList = employeeListResult.getResult();
//            List<EmployeeSDO> employeeList = platformEnhanceRepository.getEmployeeList(employeeIds.stream().distinct().collect(Collectors.toList()));
            log.info("月度计划调整明细导出employeeSDOList={}", JSONObject.toJSONString(employeeSDOList));
            if (CollectionUtils.isNotEmpty(employeeSDOList)) {
                employeeMap = employeeSDOList.stream().collect(Collectors.toMap(com.epoch.app.bcots.model.dto.EmployeeSDO::getId, o -> o));
            } else {
                employeeMap = new HashMap<>();
            }
            //批量查询组织信息
            BaselineGetOrganizationByIdsAllResponse organizationResponse = baseDataService.baselineGetOrganizationByIdsAll(BaselineGetOrganizationByIdsAllRequest.builder()
                    .ids(organizationIds.stream().distinct().collect(Collectors.toList())).build());
            if (!organizationResponse.getSuccess() || CollectionUtils.isEmpty(organizationResponse.getResult())) {
                organizationMap = new HashMap<>();
            } else {
                organizationMap = organizationResponse.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));
            }

            request.forEach(req -> {
                SalesPlanAdjustDetailExportResponse salesPlanAdjustDetail = convertSalesPlanAdjustDetailExportResponse(req, employeeMap, organizationMap);
                salesPlanAdjustDetail.setEstimateDiscount(exportRequest.getEstimateDiscount() + "%");
                salesPlanAdjustDetail.setPlanTime(exportRequest.getPlanTime());
                salesPlanAdjustDetail.setOrgBusinessUnitName(exportRequest.getOrgBusinessUnitName());
                //计算次月建议回复量、计划回复率=次月建议回复量/次月计划提报量
                String monthReturnRate = "0%";
                Integer monthCount = req.getMonthCount();
                Integer monthReturnCount = req.getMonthFirstReturnCount() + req.getMonthMiddleReturnCount() + req.getMonthLastReturnCount();
                salesPlanAdjustDetail.setMonthReturnCount(monthReturnCount);
                if (monthCount != 0 && monthReturnCount != 0) {
                    monthReturnRate = new DecimalFormat("0.00").format(new BigDecimal(monthReturnCount.toString())
                            .multiply(new BigDecimal("100"))
                            .divide(new BigDecimal(monthCount.toString()), 2, RoundingMode.HALF_UP)) + "%";
                }
                salesPlanAdjustDetail.setMonthReturnRate(monthReturnRate);
                //计算次月调整回复量
                Integer monthAdjustReturnCount = req.getMonthFirstAdjustReturnCount() + req.getMonthMiddleAdjustReturnCount() + req.getMonthLastAdjustReturnCount();
                salesPlanAdjustDetail.setMonthAdjustReturnCount(monthAdjustReturnCount);
                //计算折扣率、折扣价、修改者、创建者、各种金额
                //销售价(单位：分)
                String costInsuranceFreight;
                Double costInsurance = req.getCostInsuranceFreight();
                //到岸价(单位：分)
                Double outboundPrice = req.getOutboundPrice();
                if (costInsurance == null) {
                    costInsurance = new Double("0");
                }
                if (outboundPrice == null) {
                    outboundPrice = new Double("0");
                }
                //判断销售价是否为0，销售价为0时，不用计算直接返回
                if (costInsurance == 0) {
                    salesPlanAdjustDetail.setCostInsuranceFreight(costInsurance);
                    salesPlanAdjustDetail.setDiscountPrice(costInsurance);
                } else {
                    //销售价(单位：分)
                    costInsuranceFreight = costInsurance.toString();
                    //折扣价(单位：分)
                    String discountPrice = costInsuranceFreight;
                    //先计算折前的金额(单位：元)
                    Double beforeAdjustReturnMoney = calculateMoney(costInsuranceFreight, monthAdjustReturnCount);
                    Double beforeMonthFirstMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstCount());
                    Double beforeMonthFirstTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstTaskCount());
                    Double beforeMonthFirstAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstAdjustCount());
                    Double beforeMonthFirstAdjustReturnMoney = calculateMoney(costInsuranceFreight, req.getMonthFirstAdjustReturnCount());
                    Double beforeMonthMiddleMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleCount());
                    Double beforeMonthMiddleTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleTaskCount());
                    Double beforeMonthMiddleAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleAdjustCount());
                    Double beforeMonthMiddleAdjustReturnMoney = calculateMoney(costInsuranceFreight, req.getMonthMiddleAdjustReturnCount());
                    Double beforeMonthLastMoney = calculateMoney(costInsuranceFreight, req.getMonthLastCount());
                    Double beforeMonthLastTaskMoney = calculateMoney(costInsuranceFreight, req.getMonthLastTaskCount());
                    Double beforeMonthLastAdjustMoney = calculateMoney(costInsuranceFreight, req.getMonthLastAdjustCount());
                    Double beforeMonthLastAdjustReturnMoney = calculateMoney(costInsuranceFreight, req.getMonthLastAdjustReturnCount());
                    //折后的金额
                    Double adjustReturnMoney = beforeAdjustReturnMoney;
                    Double monthFirstMoney = beforeMonthFirstMoney;
                    Double monthFirstTaskMoney = beforeMonthFirstTaskMoney;
                    Double monthFirstAdjustMoney = beforeMonthFirstAdjustMoney;
                    Double monthFirstAdjustReturnMoney = beforeMonthFirstAdjustReturnMoney;
                    Double monthMiddleMoney = beforeMonthMiddleMoney;
                    Double monthMiddleTaskMoney = beforeMonthMiddleTaskMoney;
                    Double monthMiddleAdjustMoney = beforeMonthMiddleAdjustMoney;
                    Double monthMiddleAdjustReturnMoney = beforeMonthMiddleAdjustReturnMoney;
                    Double monthLastMoney = beforeMonthLastMoney;
                    Double monthLastTaskMoney = beforeMonthLastTaskMoney;
                    Double monthLastAdjustMoney = beforeMonthLastAdjustMoney;
                    Double monthLastAdjustReturnMoney = beforeMonthLastAdjustReturnMoney;
                    //折扣率(需要除100)
                    String estimateDiscount = String.valueOf(exportRequest.getEstimateDiscount() == 0 ? 0 : exportRequest.getEstimateDiscount() / 100);
                    //如果折扣率为0，折前和折后的金额一样
                    if (!estimateDiscount.equals("0")) {
                        //计算折扣价，单位：分
                        discountPrice = new BigDecimal(costInsuranceFreight).multiply(new BigDecimal(
                                new BigDecimal("1").subtract(new BigDecimal(estimateDiscount)).toString())).toString();
                        //计算折后的金额
                        adjustReturnMoney = calculateMoney(discountPrice, monthAdjustReturnCount);
                        monthFirstMoney = calculateMoney(discountPrice, req.getMonthFirstCount());
                        monthFirstTaskMoney = calculateMoney(discountPrice, req.getMonthFirstTaskCount());
                        monthFirstAdjustMoney = calculateMoney(discountPrice, req.getMonthFirstAdjustCount());
                        monthFirstAdjustReturnMoney = calculateMoney(discountPrice, req.getMonthFirstAdjustReturnCount());
                        monthMiddleMoney = calculateMoney(discountPrice, req.getMonthMiddleCount());
                        monthMiddleTaskMoney = calculateMoney(discountPrice, req.getMonthMiddleTaskCount());
                        monthMiddleAdjustMoney = calculateMoney(discountPrice, req.getMonthMiddleAdjustCount());
                        monthMiddleAdjustReturnMoney = calculateMoney(discountPrice, req.getMonthMiddleAdjustReturnCount());
                        monthLastMoney = calculateMoney(discountPrice, req.getMonthLastCount());
                        monthLastTaskMoney = calculateMoney(discountPrice, req.getMonthLastTaskCount());
                        monthLastAdjustMoney = calculateMoney(discountPrice, req.getMonthLastAdjustCount());
                        monthLastAdjustReturnMoney = calculateMoney(discountPrice, req.getMonthLastAdjustReturnCount());
                    }
                    salesPlanAdjustDetail.setBeforeAdjustReturnMoney(beforeAdjustReturnMoney);
                    salesPlanAdjustDetail.setAdjustReturnMoney(adjustReturnMoney);
                    salesPlanAdjustDetail.setBeforeMonthFirstMoney(beforeMonthFirstMoney);
                    salesPlanAdjustDetail.setMonthFirstMoney(monthFirstMoney);
                    salesPlanAdjustDetail.setBeforeMonthFirstTaskMoney(beforeMonthFirstTaskMoney);
                    salesPlanAdjustDetail.setMonthFirstTaskMoney(monthFirstTaskMoney);
                    salesPlanAdjustDetail.setBeforeMonthFirstAdjustMoney(beforeMonthFirstAdjustMoney);
                    salesPlanAdjustDetail.setMonthFirstAdjustMoney(monthFirstAdjustMoney);
                    salesPlanAdjustDetail.setBeforeMonthFirstAdjustReturnMoney(beforeMonthFirstAdjustReturnMoney);
                    salesPlanAdjustDetail.setMonthFirstAdjustReturnMoney(monthFirstAdjustReturnMoney);

                    salesPlanAdjustDetail.setBeforeMonthMiddleMoney(beforeMonthMiddleMoney);
                    salesPlanAdjustDetail.setMonthMiddleMoney(monthMiddleMoney);
                    salesPlanAdjustDetail.setBeforeMonthMiddleTaskMoney(beforeMonthMiddleTaskMoney);
                    salesPlanAdjustDetail.setMonthMiddleTaskMoney(monthMiddleTaskMoney);
                    salesPlanAdjustDetail.setBeforeMonthMiddleAdjustMoney(beforeMonthMiddleAdjustMoney);
                    salesPlanAdjustDetail.setMonthMiddleAdjustMoney(monthMiddleAdjustMoney);
                    salesPlanAdjustDetail.setBeforeMonthMiddleAdjustReturnMoney(beforeMonthMiddleAdjustReturnMoney);
                    salesPlanAdjustDetail.setMonthMiddleAdjustReturnMoney(monthMiddleAdjustReturnMoney);

                    salesPlanAdjustDetail.setBeforeMonthLastMoney(beforeMonthLastMoney);
                    salesPlanAdjustDetail.setMonthLastMoney(monthLastMoney);
                    salesPlanAdjustDetail.setBeforeMonthLastTaskMoney(beforeMonthLastTaskMoney);
                    salesPlanAdjustDetail.setMonthLastTaskMoney(monthLastTaskMoney);
                    salesPlanAdjustDetail.setBeforeMonthLastAdjustMoney(beforeMonthLastAdjustMoney);
                    salesPlanAdjustDetail.setMonthLastAdjustMoney(monthLastAdjustMoney);
                    salesPlanAdjustDetail.setBeforeMonthLastAdjustReturnMoney(beforeMonthLastAdjustReturnMoney);
                    salesPlanAdjustDetail.setMonthLastAdjustReturnMoney(monthLastAdjustReturnMoney);

                    //计算完毕以后将价格转为元
                    costInsuranceFreight = fenToYuan(costInsurance).toString();
                    discountPrice = fenToYuan(Double.valueOf(discountPrice)).toString();
                    salesPlanAdjustDetail.setCostInsuranceFreight(Double.valueOf(costInsuranceFreight));
                    salesPlanAdjustDetail.setDiscountPrice(Double.valueOf(discountPrice));
                }
                //计算到岸金额
                if (outboundPrice == 0) {
                    salesPlanAdjustDetail.setOutboundPrice(outboundPrice);
                } else {
                    String outboundPriceString = outboundPrice.toString();
                    Double beforeMonthOutboundMoney = calculateMoney(outboundPriceString, req.getMonthCount());
                    Double beforeTaskOutboundMoney = calculateMoney(outboundPriceString, req.getTaskCount());
                    Double beforeAdjustOutboundMoney = calculateMoney(outboundPriceString, req.getAdjustCount());
                    Double beforeAdjustReturnOutboundMoney = calculateMoney(outboundPriceString, monthAdjustReturnCount);
                    Double beforeMonthFirstOutboundMoney = calculateMoney(outboundPriceString, req.getMonthFirstCount());
                    Double beforeMonthFirstTaskOutboundMoney = calculateMoney(outboundPriceString, req.getMonthFirstTaskCount());
                    Double beforeMonthFirstAdjustOutboundMoney = calculateMoney(outboundPriceString, req.getMonthFirstAdjustCount());
                    Double beforeMonthFirstAdjustReturnOutboundMoney = calculateMoney(outboundPriceString, req.getMonthFirstAdjustReturnCount());
                    Double beforeMonthMiddleOutboundMoney = calculateMoney(outboundPriceString, req.getMonthMiddleCount());
                    Double beforeMonthMiddleTaskOutboundMoney = calculateMoney(outboundPriceString, req.getMonthMiddleTaskCount());
                    Double beforeMonthMiddleAdjustOutboundMoney = calculateMoney(outboundPriceString, req.getMonthMiddleAdjustCount());
                    Double beforeMonthMiddleAdjustReturnOutboundMoney = calculateMoney(outboundPriceString, req.getMonthMiddleAdjustReturnCount());
                    Double beforeMonthLastOutboundMoney = calculateMoney(outboundPriceString, req.getMonthLastCount());
                    Double beforeMonthLastTaskOutboundMoney = calculateMoney(outboundPriceString, req.getMonthLastTaskCount());
                    Double beforeMonthLastAdjustOutboundMoney = calculateMoney(outboundPriceString, req.getMonthLastAdjustTotalCount());
                    Double beforeMonthLastAdjustReturnOutboundMoney = calculateMoney(outboundPriceString, req.getMonthLastAdjustReturnCount());

                    salesPlanAdjustDetail.setOutboundPrice(fenToYuan(outboundPrice));
                    salesPlanAdjustDetail.setBeforeMonthOutboundMoney(beforeMonthOutboundMoney);
                    salesPlanAdjustDetail.setBeforeTaskOutboundMoney(beforeTaskOutboundMoney);
                    salesPlanAdjustDetail.setBeforeAdjustOutboundMoney(beforeAdjustOutboundMoney);
                    salesPlanAdjustDetail.setBeforeAdjustReturnOutboundMoney(beforeAdjustReturnOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthFirstOutboundMoney(beforeMonthFirstOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthFirstTaskOutboundMoney(beforeMonthFirstTaskOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthFirstAdjustOutboundMoney(beforeMonthFirstAdjustOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthFirstAdjustReturnOutboundMoney(beforeMonthFirstAdjustReturnOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthMiddleOutboundMoney(beforeMonthMiddleOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthMiddleTaskOutboundMoney(beforeMonthMiddleTaskOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthMiddleAdjustOutboundMoney(beforeMonthMiddleAdjustOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthMiddleAdjustReturnOutboundMoney(beforeMonthMiddleAdjustReturnOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthLastOutboundMoney(beforeMonthLastOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthLastTaskOutboundMoney(beforeMonthLastTaskOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthLastAdjustOutboundMoney(beforeMonthLastAdjustOutboundMoney);
                    salesPlanAdjustDetail.setBeforeMonthLastAdjustReturnOutboundMoney(beforeMonthLastAdjustReturnOutboundMoney);
                }
                convertMoneyToString(salesPlanAdjustDetail);
                responses.add(salesPlanAdjustDetail);
            });
            return Result.success(responses);
        } catch (Exception e) {
            log.error("计划调整明细导出失败", e);
            return Result.fail("OTS-02-006-00-16-008", ErrorMessage.code("OTS-02-006-00-16-008", null).getDisplayErrorMessage());
        }
    }

    private Double calculateMoney(String price, Integer count) {
        if (count == 0) {
            return new Double("0");
        }
        String money = new DecimalFormat("0.00").format(new BigDecimal(price)
                .multiply(new BigDecimal(count.toString()))
                .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
        return Double.valueOf(money);
    }

    public Double fenToYuan(Double price) {
        if (price == 0) {
            return price;
        }
        String money = new DecimalFormat("0.00").format(new BigDecimal(price.toString())
                .divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP));
        return Double.valueOf(money);
    }

//    private SalesPlanAdjustDetailExportResponse convertSalesPlanAdjustDetailExportResponse(SalesPlanAdjustDetailExportRequest req, Map<String, EmployeeSDO> map) {
//        SalesPlanAdjustDetailExportResponse salesPlanAdjustDetail = new SalesPlanAdjustDetailExportResponse();
//        BeanUtils.copyProperties(req, salesPlanAdjustDetail);
//        salesPlanAdjustDetail.setEstimateDiscount(req.getEstimateDiscount() + "%");
//        //接口返回的金额都是分，需要转成元
//        salesPlanAdjustDetail.setBeforeMonthContractMoney(fenToYuan(req.getBeforeMonthContractMoney()));
//        salesPlanAdjustDetail.setMonthContractMoney(fenToYuan(req.getMonthContractMoney()));
//        salesPlanAdjustDetail.setBeforeMonthMoney(fenToYuan(req.getBeforeMonthMoney()));
//        salesPlanAdjustDetail.setMonthMoney(fenToYuan(req.getMonthMoney()));
//        salesPlanAdjustDetail.setBeforeTaskMoney(fenToYuan(req.getBeforeTaskMoney()));
//        salesPlanAdjustDetail.setTaskMoney(fenToYuan(req.getTaskMoney()));
//        salesPlanAdjustDetail.setBeforeAdjustMoney(fenToYuan(req.getBeforeAdjustMoney()));
//        salesPlanAdjustDetail.setAdjustMoney(fenToYuan(req.getAdjustMoney()));
//
//        salesPlanAdjustDetail.setUpdater(map.get(req.getUpdater().replace("CZ_", "")).getName());
//        salesPlanAdjustDetail.setCreator(map.get(req.getCreator().replace("CZ_", "")).getName());
//        return salesPlanAdjustDetail;
//    }

    private SalesPlanAdjustDetailExportResponse convertSalesPlanAdjustDetailExportResponse(SalesPlanAdjustDetailExportRequest req, Map<String, com.epoch.app.bcots.model.dto.EmployeeSDO> employeeMap, Map<String, OrganizationSDO> organizationMap) {
        SalesPlanAdjustDetailExportResponse salesPlanAdjustDetail = new SalesPlanAdjustDetailExportResponse();
        BeanUtils.copyProperties(req, salesPlanAdjustDetail);
        salesPlanAdjustDetail.setBeforeContractSatisfaction(Optional.ofNullable(req.getBeforeContractSatisfaction()).orElse(0d) + "%");
        salesPlanAdjustDetail.setContractSatisfaction(Optional.ofNullable(req.getContractSatisfaction()).orElse(0d) + "%");
        //接口返回的金额都是分，需要转成元
        salesPlanAdjustDetail.setBeforeMonthContractMoney(fenToYuan(req.getBeforeMonthContractMoney()));
        salesPlanAdjustDetail.setMonthContractMoney(fenToYuan(req.getMonthContractMoney()));
        salesPlanAdjustDetail.setBeforeMonthMoney(fenToYuan(req.getBeforeMonthMoney()));
        salesPlanAdjustDetail.setMonthMoney(fenToYuan(req.getMonthMoney()));
        salesPlanAdjustDetail.setBeforeTaskMoney(fenToYuan(req.getBeforeTaskMoney()));
        salesPlanAdjustDetail.setTaskMoney(fenToYuan(req.getTaskMoney()));
        salesPlanAdjustDetail.setBeforeAdjustMoney(fenToYuan(req.getBeforeAdjustMoney()));
        salesPlanAdjustDetail.setAdjustMoney(fenToYuan(req.getAdjustMoney()));

        salesPlanAdjustDetail.setUpdater(JSONObject.parseObject(req.getUpdater()).get("realName").toString());
        salesPlanAdjustDetail.setCreator(JSONObject.parseObject(req.getCreator()).get("realName").toString());

        if (MapUtils.isNotEmpty(employeeMap) && null != employeeMap.get(req.getManageEmployeeId())) {
            salesPlanAdjustDetail.setManageEmployeeName(employeeMap.get(req.getManageEmployeeId()).getName());
            salesPlanAdjustDetail.setManageEmployeeNick(employeeMap.get(req.getManageEmployeeId()).getNick());
        }
        if (MapUtils.isNotEmpty(organizationMap)) {
            if (null != organizationMap.get(req.getOrgSalesChannelCode())) {
                salesPlanAdjustDetail.setOrgSalesChannelName(organizationMap.get(req.getOrgSalesChannelCode()).getName());
            }
            if (null != organizationMap.get(req.getOrgSalesDepartmentCode())) {
                salesPlanAdjustDetail.setOrgSalesDepartmentName(organizationMap.get(req.getOrgSalesDepartmentCode()).getName());
            }
        }
        return salesPlanAdjustDetail;
    }

    private boolean isJsonObject(String valueAsString) {
        return valueAsString.startsWith("{") && valueAsString.endsWith("}") && valueAsString.contains(":");
    }

    private void convertMoneyToString(SalesPlanAdjustDetailExportResponse salesPlanAdjustDetail) {
        salesPlanAdjustDetail.setCostInsuranceFreightString(keepTwoDecimal(salesPlanAdjustDetail.getCostInsuranceFreight()));
        salesPlanAdjustDetail.setDiscountPriceString(keepTwoDecimal(salesPlanAdjustDetail.getDiscountPrice()));
        salesPlanAdjustDetail.setBeforeMonthContractMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthContractMoney()));
        salesPlanAdjustDetail.setMonthContractMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthContractMoney()));

        salesPlanAdjustDetail.setBeforeMonthMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMoney()));
        salesPlanAdjustDetail.setMonthMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthMoney()));
        salesPlanAdjustDetail.setBeforeTaskMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeTaskMoney()));
        salesPlanAdjustDetail.setTaskMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getTaskMoney()));
        salesPlanAdjustDetail.setBeforeAdjustMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeAdjustMoney()));
        salesPlanAdjustDetail.setAdjustMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getAdjustMoney()));
        salesPlanAdjustDetail.setBeforeAdjustReturnMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeAdjustReturnMoney()));
        salesPlanAdjustDetail.setAdjustReturnMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getAdjustReturnMoney()));

        salesPlanAdjustDetail.setBeforeMonthFirstMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthFirstMoney()));
        salesPlanAdjustDetail.setMonthFirstMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthFirstMoney()));
        salesPlanAdjustDetail.setBeforeMonthFirstTaskMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthFirstTaskMoney()));
        salesPlanAdjustDetail.setMonthFirstTaskMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthFirstTaskMoney()));
        salesPlanAdjustDetail.setBeforeMonthFirstAdjustMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthFirstAdjustMoney()));
        salesPlanAdjustDetail.setMonthFirstAdjustMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthFirstAdjustMoney()));
        salesPlanAdjustDetail.setBeforeMonthFirstAdjustReturnMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthFirstAdjustReturnMoney()));
        salesPlanAdjustDetail.setMonthFirstAdjustReturnMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthFirstAdjustReturnMoney()));

        salesPlanAdjustDetail.setBeforeMonthMiddleMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMiddleMoney()));
        salesPlanAdjustDetail.setMonthMiddleMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthMiddleMoney()));
        salesPlanAdjustDetail.setBeforeMonthMiddleTaskMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMiddleTaskMoney()));
        salesPlanAdjustDetail.setMonthMiddleTaskMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthMiddleTaskMoney()));
        salesPlanAdjustDetail.setBeforeMonthMiddleAdjustMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMiddleAdjustMoney()));
        salesPlanAdjustDetail.setMonthMiddleAdjustMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthMiddleAdjustMoney()));
        salesPlanAdjustDetail.setBeforeMonthMiddleAdjustReturnMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMiddleAdjustReturnMoney()));
        salesPlanAdjustDetail.setMonthMiddleAdjustReturnMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthMiddleAdjustReturnMoney()));

        salesPlanAdjustDetail.setBeforeMonthLastMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthLastMoney()));
        salesPlanAdjustDetail.setMonthLastMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthLastMoney()));
        salesPlanAdjustDetail.setBeforeMonthLastTaskMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthLastTaskMoney()));
        salesPlanAdjustDetail.setMonthLastTaskMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthLastTaskMoney()));
        salesPlanAdjustDetail.setBeforeMonthLastAdjustMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthLastAdjustMoney()));
        salesPlanAdjustDetail.setMonthLastAdjustMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthLastAdjustMoney()));
        salesPlanAdjustDetail.setBeforeMonthLastAdjustReturnMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthLastAdjustReturnMoney()));
        salesPlanAdjustDetail.setMonthLastAdjustReturnMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getMonthLastAdjustReturnMoney()));

        //到岸价
        salesPlanAdjustDetail.setOutboundPriceString(keepTwoDecimal(salesPlanAdjustDetail.getOutboundPrice()));
        salesPlanAdjustDetail.setBeforeMonthOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthOutboundMoney()));
        salesPlanAdjustDetail.setBeforeTaskOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeTaskOutboundMoney()));
        salesPlanAdjustDetail.setBeforeAdjustOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeAdjustOutboundMoney()));
        salesPlanAdjustDetail.setBeforeAdjustReturnOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeAdjustReturnOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthFirstOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthFirstOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthFirstTaskOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthFirstTaskOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthFirstAdjustOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthFirstAdjustOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthFirstAdjustReturnOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthFirstAdjustReturnOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthMiddleOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMiddleOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthMiddleTaskOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMiddleTaskOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthMiddleAdjustOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMiddleAdjustOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthMiddleAdjustReturnOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthMiddleAdjustReturnOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthLastOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthLastOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthLastTaskOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthLastTaskOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthLastAdjustOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthLastAdjustOutboundMoney()));
        salesPlanAdjustDetail.setBeforeMonthLastAdjustReturnOutboundMoneyString(keepTwoDecimal(salesPlanAdjustDetail.getBeforeMonthLastAdjustReturnOutboundMoney()));
    }

    //保留两位小数
    private String keepTwoDecimal(Double source) {
        if (source == null || source == 0) {
            return "0.00";
        }
        return new DecimalFormat("0.00").format(new BigDecimal(source.toString()));
    }

    @Override
    @FacadeInvoker
    public Result<FirstLoginEmailSDO> firstLoginEmail(FirstLoginEmailRequest firstLoginEmailRequest) {
        return salesPlanAdjustDetailFileRepository.firstLoginEmail(firstLoginEmailRequest);
    }

    @Override
    @FacadeInvoker
    public Result<ResetPasswordEmailSDO> resetPasswordEmail(ResetPasswordEmailRequest resetPasswordEmailRequest) {
        return salesPlanAdjustDetailFileRepository.resetPasswordEmail(resetPasswordEmailRequest);
    }

    /**
     * 修改密码
     *
     * @param changePasswordRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<Boolean> changePassword(ChangePasswordRequest changePasswordRequest) {
        //判断是否传参
        if (StringUtils.isBlank(changePasswordRequest.getEmail())) {
            throw new FacadeException("OTS-01-001-01-15-005");
        }
        if (StringUtils.isBlank(changePasswordRequest.getVerificationCode())) {
            throw new FacadeException("OTS-01-001-01-15-008");
        }
        if (StringUtils.isBlank(changePasswordRequest.getFirstPassword())) {
            throw new FacadeException("OTS-01-001-01-15-009");
        }
        if (StringUtils.isBlank(changePasswordRequest.getSecondPassword())) {
            throw new FacadeException("OTS-01-001-01-15-010");
        }
        //根据邮箱获取当前要修改的员工
        QueryEmployeeAndOrganizationRequest request = new QueryEmployeeAndOrganizationRequest();
        request.setEmail(changePasswordRequest.getEmail());
        QueryEmployeeAndOrganizationResponse response = baseDataService.queryEmployeeAndOrganization(request);
        if (Objects.isNull(response)) {
            throw new FacadeException("OTS-01-001-01-15-006");
        }
        com.epoch.app.bcots.model.dto.EmployeeSDO employeeSDO = response.getEmployeeSDO();
        if (Objects.isNull(employeeSDO)) {
            throw new FacadeException("OTS-01-001-01-15-007");
        }

        //获取发送的验证码
        String verificationKey = "Verification_Code" + changePasswordRequest.getEmail();
        String verificationCode = epochCacheService.get(BcOtsConstants.REDIS_CACHE_CODE(), verificationKey);
        if (StringUtils.isBlank(verificationCode)) {
            throw new FacadeException("OTS-01-001-01-15-011");
        }

        //判断验证码是否一致
        if (!changePasswordRequest.getVerificationCode().equals(verificationCode)) {
            throw new FacadeException("OTS-01-001-01-15-013");
        }
        //判断第一次输入的密码和二次确认密码是否一致
        if (!changePasswordRequest.getFirstPassword().equals(changePasswordRequest.getSecondPassword())) {
            throw new FacadeException("OTS-01-001-01-15-012");
        }

        //如果密码一致  并且 验证码正确 那么让其修改密码  保存
        EmployeeResetPasswordsRequest resetPasswordsRequest = new EmployeeResetPasswordsRequest();
        resetPasswordsRequest.setEmployeeId(employeeSDO.getId());
        resetPasswordsRequest.setPassword(changePasswordRequest.getFirstPassword());
        resetPasswordsRequest.setApiContext(employeeSDO);
        try {
            bcOtsService.employeeResetPasswords(resetPasswordsRequest);
        } catch (Exception e) {
            log.error("OTS-01-001-01-15-014", e);
            throw new FacadeException("OTS-01-001-01-15-014");
        }
        //验证码用完之后需要进行删除
        epochCacheService.remove(BcOtsConstants.REDIS_CACHE_CODE(), Lists.newArrayList(verificationKey));
        return Result.success(true);
    }


    /**
     * 账号停用
     *
     * @param resetPasswordEmailRequest
     * @return
     */
    @Override
    @FacadeInvoker
    public Result<AccountDeactivationSDO> accountDeactivation(ResetPasswordEmailRequest resetPasswordEmailRequest) {
        //判断是否传递邮箱
        if (StringUtils.isBlank(resetPasswordEmailRequest.getEmail())) {
            throw new FacadeException("OTS-01-001-01-15-005");
        }
        //查询模板
        BoNotificationConfigGetListResponse listResponse = queryTemplate();
        if (Objects.isNull(listResponse) || CollectionUtils.isEmpty(listResponse.getResult())) {
            throw new FacadeException("OTS-01-001-01-15-003");
        }
        //查询到对应的模板 进行封装返回
        Map notificationMap = (Map) listResponse.getResult().get(0);
        //如果该模板的状态为禁用状态 提示该模板以禁用 如需使用请启用
        if (notificationMap.get("status").equals(0)) {
            throw new FacadeException("OTS-01-001-01-15-022");
        }
        AccountDeactivationSDO accountDeactivationSDO = new AccountDeactivationSDO();
        String label = notificationMap.get("label").toString();
        String content = notificationMap.get("content").toString();
        if (StringUtils.isNotBlank(label)) {
            accountDeactivationSDO.setTitle(label);
        }
        if (StringUtils.isNotBlank(content)) {
            accountDeactivationSDO.setContent(content);
        }
        accountDeactivationSDO.setRecipient(resetPasswordEmailRequest.getEmail());
        return Result.success(accountDeactivationSDO);
    }

    /**
     * 货品类目维护
     *
     * @return
     */
    @Override
    public Result<ResetPasswordEmailSDO> categoryMaintenance() {
        //查询邮件通知模板
        BoNotificationConfigGetListResponse configGetListResponse = notificationConfigService.boNotificationConfigGetList(BoNotificationConfigGetListRequest.builder().title("5").build());
        if (Objects.isNull(configGetListResponse) || CollectionUtils.isEmpty(configGetListResponse.getResult())) {
            throw new FacadeException("OTS-01-001-01-15-003");
        }
        //模板存在 需要判断该模板当前的状态是否为启用状态
        Map notificationMap = (Map) configGetListResponse.getResult().get(0);
        //如果该模板的状态为禁用状态 提示该模板以禁用 如需使用请启用
        if (notificationMap.get("status").equals(0)) {
            throw new FacadeException("OTS-01-001-01-15-022");
        }
        //模板存在并且启用状态 那么获取其中配置的收件人的邮箱与发送内容进行返回
        if (StringUtils.isBlank(notificationMap.get("recipient").toString())) {
            throw new FacadeException("OTS-01-001-01-15-023");
        }
        String recipient = notificationMap.get("recipient").toString();
        ResetPasswordEmailSDO resetPasswordEmailSDO = new ResetPasswordEmailSDO();
        //收件人
        resetPasswordEmailSDO.setRecipient(recipient);
        //通知内容
        if (StringUtils.isNotBlank(notificationMap.get("content").toString())) {
            String content = notificationMap.get("content").toString();
            //通知内容中的链接进行拼接
            String messagecontent = MessageFormat.format(content, BcOtsConstants.MAINTAIN_URL());
            resetPasswordEmailSDO.setContent(messagecontent);
        }
        resetPasswordEmailSDO.setTitle(notificationMap.get("label").toString());

        //发送后 进行保存发送记录
        SendHistoryRecordSDO sendHistoryRecordSDO = new SendHistoryRecordSDO();
        sendHistoryRecordSDO.setNotificationId(notificationMap.get("id").toString());
        sendHistoryRecordSDO.setLabel(notificationMap.get("label").toString());
        sendHistoryRecordSDO.setTitle("5");
        sendHistoryRecordSDO.setSendMethod(1);
        sendHistoryRecordSDO.setSendTime(new Date());
        sendHistoryRecordSDO.setRecipient(recipient);
        if (sendHistoryRecordSDO == null) {
            sendHistoryRecordSDO.setStatus(0);
        }
        sendHistoryRecordSDO.setStatus(1);
        sendHistoryRecordRepository.save(sendHistoryRecordSDO);
        return Result.success(resetPasswordEmailSDO);
    }

    private BoNotificationConfigGetListResponse queryTemplate() {
        BoNotificationConfigGetListRequest boNotificationConfigGetListRequest = new BoNotificationConfigGetListRequest();
        boNotificationConfigGetListRequest.setTitle("4");
        BoNotificationConfigGetListResponse listResponse = notificationConfigService.boNotificationConfigGetList(boNotificationConfigGetListRequest);
        return listResponse;
    }
}
